import { CaptchaService } from '@midwayjs/captcha'
import { Body, Controller, Get, httpError, Inject, Post } from '@midwayjs/core'
import { Context } from '@midwayjs/koa'
import { ApiOperation, ApiResponse, ApiTags } from '@midwayjs/swagger'
import { Validate } from '@midwayjs/validate'

import { APP_MESSAGES } from '@/constant'

import { LoginDTO } from './auth.dto'
import { AuthService } from './auth.service'
import { GetCaptchaVO, LoginVO } from './auth.vo'

@ApiTags('鉴权接口')
@Controller('/auth')
export class AuthController {
  @Inject()
  ctx: Context

  @Inject()
  authService: AuthService

  @Inject()
  captchaService: CaptchaService

  @ApiOperation({ summary: '登录' })
  @ApiResponse({ status: 200, type: LoginVO })
  @Post('/login')
  @Validate()
  async login(@Body() dto: LoginDTO) {
    const passed = await this.captchaService.check(
      dto.captchaId,
      dto.captchaValue
    )

    if (!passed) {
      throw new httpError.BadRequestError(APP_MESSAGES.CAPTCHA_NOT_CORRECT)
    }

    return await this.authService.handleLogin(dto)
  }

  @ApiOperation({ summary: '退出' })
  @Post('/logout')
  async logout() {
    await this.authService.handleLogout()
  }

  @ApiOperation({ summary: '获取验证码' })
  @ApiResponse({ status: 200, type: GetCaptchaVO })
  @Get('/captcha')
  async getCaptcha() {
    return await this.captchaService.image({
      width: 90,
      height: 40,
      noise: 2,
      size: 4
    })
  }
}
